package gp_fifo_generator;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Parameters {
	public List<String> fileList;
	public Map<String, String> paramHash;
	
    public boolean initFromFile( String path ){
	  Pattern  _section  = Pattern.compile( "\\s*\\[([^]]*)\\]\\s*" );
	  Pattern  _keyValue = Pattern.compile( "\\s*([^=]*)=(.*)" );
		  Map< String,  Map< String,  String >>  _entries  = new HashMap<>();
 
	      try{
	    	 BufferedReader br = new BufferedReader( new FileReader( path ));
	         String line;
	         String section = null;
	         while(( line = br.readLine()) != null ) {
	            Matcher m = _section.matcher( line );
	            if( m.matches()) {
	               section = m.group( 1 ).trim();
	            }
	            else if( section != null ) {
	               m = _keyValue.matcher( line );
	               if( m.matches()) {
	                  String key   = m.group( 1 ).trim();
	                  String value = m.group( 2 ).trim();
	                  Map< String, String > kv = _entries.get( section );
	                  if( kv == null ) {
	                     _entries.put( section, kv = new HashMap<>());   
	                  }
	                  kv.put( key, value );
	               }
	            }
	         }
	         br.close();
	      }catch(IOException e){
	    	  System.out.println("Config file doesn't exist or parsing error occured");
    	  return false;
      }
      
      
      if (!initFileList(_entries) || !initParamList(_entries)){
    	  System.out.println("Parsing error, please check config file");
    	  return false;
      }
      
      return true;
   }
   
    private boolean initFileList(Map< String,  Map< String,  String >> entries){
	   Map< String, String > files = entries.get("FILES");
	   if (null == files){
		   return false;
	   }
	   fileList = new ArrayList<String>(files.values());
	   if (null == fileList){
		   return false;
	   }
	   return true;
	}
   
    private boolean initParamList(Map< String,  Map< String,  String >> entries){
    	paramHash = entries.get("PARAMETERS");
	   	return true;
    }

}
